package cn.com.wxd.service.dispatch.logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.service.dispatch.engine.CustomConfigInfo;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.file.MyFileUtil;

/**
 * 对队列中的数据进行刷入到文件系统中
 * Created by ComXu on 2017/5/18.
 */
public class CustomTaskLoggerWriter implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(CustomTaskLoggerWriter.class);

    @Override
    public void run() {
        LinkedBlockingQueue<CustomTaskLoggerEntity> queues = CustomTaskLoggerQueues.getQueues();
        while (!queues.isEmpty()) {
            CustomTaskLoggerEntity ctle;
            ctle = queues.poll(); // 返回队列中的第一个元素
            //刷入到文件中
            File outDir = new File(CustomConfigInfo.getLoggerDirPath());
            if (!outDir.exists()) {
                outDir.mkdirs();
            }
            String logName = ctle.getTaskName();
            if (logName == null) {
                logName = "default";
            }
            logName = logName.replaceAll("\\\\", "_");
            logName = logName.replaceAll("/", "_");
            logName = logName.trim();
            File outFile = new File(CustomConfigInfo.getLoggerDirPath()
                    + File.separator + ctle.getTaskId() + "_" + logName + ".log");
            try {
                if (!outFile.exists()) {
                    outFile.createNewFile();
                }
                if (outFile.length() / 1024 / 1024 >= 5) {  //文件大于5M就重新起一个文件
                    MyFileUtil.renameFile(CustomConfigInfo.getLoggerDirPath(), ctle.getTaskId() +
                                    "_" + DateUtil.getTimestamp() + ".log",
                            ctle.getTaskId() + "_" + logName + ".log" + "." + DateUtil.getTimestamp());
                }
                String line = DateUtil.getDatetimeStr("yyyy-MM-dd HH:mm:ss");
                line += " " + ctle.getLevel();
                line += " TaskId:" + ctle.getTaskId();
                line += " - " + ctle.getMessage();
                writeStr(outFile, line);
            } catch (IOException e) {
                log.error("", e);
            }
            //TODO 关于写入数据库，之后在说
        }

    }

    private void writeStr(File file, String str) throws IOException {
        FileWriter writer = null;
        try {
            writer = new FileWriter(file, true);
            writer.write(str + System.getProperty("line.separator"));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            log.error("", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
